package stu.day1_day8;

import java.util.ArrayList;
import java.util.List;

public class LeetCode735 {
    public int[] asteroidCollision(int[] asteroids) {
        List<Integer> leftAsteroids = new ArrayList<>();
        List<Integer> stack = new ArrayList<>();

        for (int asteroid : asteroids) {
            if (asteroid > 0) {
                stack.add(asteroid);
            } else if (asteroid < 0) {
                if (stack.isEmpty()) {
                    leftAsteroids.add(asteroid);
                } else {
                    while (!stack.isEmpty() && Math.abs(asteroid) > stack.get(stack.size() - 1)) {
                        stack.remove(stack.size() - 1);
                    }
                    if (!stack.isEmpty() && Math.abs(asteroid) == stack.get(stack.size() - 1)) {
                        stack.remove(stack.size() - 1);
                        continue;
                    }
                    if (stack.isEmpty()) {
                        leftAsteroids.add(asteroid);
                    }
                }
            }
        }

        int[] result = new int[leftAsteroids.size() + stack.size()];
        int index = 0;

        for (int left : leftAsteroids) {
            result[index++] = left;
        }

        for (int right : stack) {
            result[index++] = right;
        }

        return result;
    }


}
